import datetime
import json
import time
import pyautogui
import os
import openocd
import GetPort
import binFile

class Bank:
    def __init__(self):
        self.addressStart = None
        self.addressEnd = None
class downloader:
    def __init__(self):
        self.cf = None
        self.name = None
        self.allname = None
        self.add = None
        self.bank = Bank
        self.length = None
        self.XPXH = None
        self.BBH = None
        self.way = None
        self.jtag = None
        self.password = None
        self.target_value =None
        self.target_value_otp = None
        self.target_value_otp2 = None
        self.error_value = None
        self.rizhiFile = "D:/Desktop/1.2.14.0.3/haawking_downloader_1.2.14.0.3Beta9/log.log"
        self.openocdBinName = None
        self.hexBinName = None
        self.app = openocd.Openocd()
        self.gpt = GetPort.GetPort()
        self.xpxh_y = None
        self.bbh_y = None


    def choose(self,url):
        folder_window_position = pyautogui.locateOnScreen(url)
        if folder_window_position is None:
            print(pyautogui.locateOnScreen(url)+ "无法找到文件夹窗口")
            self.choose(url)
        folder_window_center = pyautogui.center(folder_window_position)
        pyautogui.moveTo(folder_window_center, duration=1)
        pyautogui.click()
        time.sleep(1)
    def find(self,url):
        folder_window_position = pyautogui.locateOnScreen(url)
        if folder_window_position is None:
            print(pyautogui.locateOnScreen(url)+ "无法找到文件夹窗口")
            self.find(url)
        folder_window_center = pyautogui.center(folder_window_position)
        return folder_window_center
    def chongfu(self,url):
        folder_window_position = pyautogui.locateOnScreen(url)
        print(folder_window_position)
        if folder_window_position is None:
            self.cf = "不重复"
            print(self.cf)
        else:
            self.cf = "数据中有重复数据"
            print(self.cf)
        return self.cf

    # 选择芯片连接方式
    def lianjiefangshi(self):
        ljfs = self.find("./image/LJFS.png")
        pyautogui.click(x=ljfs.x + 50, y=ljfs.y)
        time.sleep(1)

        pyautogui.click(y=ljfs.y + 20)
        time.sleep(1)

    # 选择芯片和型号
    def caozuo(self):
        # print(xpxh_y,bbh_y)
        xinpxh = self.find("./image/XPXH.png")
        pyautogui.click(x=xinpxh.x + 50, y=xinpxh.y)
        time.sleep(1)
        pyautogui.click(x=xinpxh.x + 50, y=xinpxh.y + self.xpxh_y)
        time.sleep(1)
        banbenhao = self.find("./image/BBH.png")
        pyautogui.click(x=banbenhao.x + 50, y=banbenhao.y)
        time.sleep(1)
        pyautogui.click(x=banbenhao.x + 50, y=banbenhao.y + self.bbh_y)
        time.sleep(1)
        self.lianjiefangshi()
        time.sleep(1)
        refresh = self.find("./image/refresh.png")
        pyautogui.click(refresh)
        lianjiefangshi = self.find("./image/LJFS.png")
        pyautogui.click(x=lianjiefangshi.x + 50, y=lianjiefangshi.y)
        time.sleep(1)
        pyautogui.click(x=lianjiefangshi.x + 50, y=lianjiefangshi.y + 20)
        time.sleep(1)
    #勾选选项
    def gouxuan(self):

        pyautogui.click(self.find("./image/erase_flash.png"))
        time.sleep(1)
        pyautogui.click(self.find("./image/Empty_Check.png"))
        time.sleep(1)
        pyautogui.click(self.find("./image/down_flash.png"))
        time.sleep(1)
        pyautogui.click(self.find("./image/Compare_Checksum.png"))
        time.sleep(1)
        # pyautogui.click(self.find("./image/run.png"))
    # 生成bin文件并对比
    def readfile(self, file,name):
        time.sleep(1)
        isOK = True
        for i in range(len(self.bank)):
            self.app.send(f'{self.allname} unlock 0')
            time.sleep(1)

            if self.allname == "hxs320f28034_cdd" or self.allname == "hxm32g407_cdd":
                self.app.send("riscv.cpu riscv set_mem_access sysbus")
                time.sleep(1)
                self.app.send("mww 0x7af890 0x5")
                time.sleep(1)

            self.app.send(f'dump_image {self.openocdBinName}bank{i}.bin 0x{str(self.bank[i].get("addressStart"))} {self.length}')
            time.sleep(20)
            os.system(f'java -cp com.haawking.core_1.1.7.jar HexToBin {self.file} {self.hexBinName}bank{i}.bin {str(self.bank[i].get("addressStart"))} {str(self.bank[i].get("addressEnd"))}')
            time.sleep(5)
            hexToBin = binFile.GetFileMd5(f'{self.hexBinName}bank{i}.bin')
            openocdToBin = binFile.GetFileMd5(f'{self.openocdBinName}bank{i}.bin')
            if (hexToBin == openocdToBin):
                result = "Success"
                if isOK:
                    isOK = True
            else:
                result = "Failure"
                isOK = False
                # 将数据存放到result.txt文件
            with open("result.txt", "a") as f:
                f.write(f'{self.allname},{result},{file},HexToBin:{hexToBin},openocd:{openocdToBin},{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} "\n')
        with open("result.txt", "a") as f:
            f.write(f'{self.allname}, bin文件对比结果为: {isOK},{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")} "\n')
        self.app.setEvent()
        self.app.close()

    def list_files_in_folder(self,folder_path):
        try:
            # 获取文件夹中的所有文件
            files = os.listdir(folder_path)
            print(files)
            for file in files:
                self.file = f"./case/{self.name}/"+file
                self.openocdBinName = "D:/hx_downloader_tool/downloader/binfile/openocd_bin/"+file
                self.hexBinName = "D:/hx_downloader_tool/downloader/binfile/HexToBin/"+file
                # 拼接文件夹路径和文件名
                file_path = os.path.join(folder_path, file)
                # 判断是否为文件
                if os.path.isfile(file_path):
                    print(self.xpxh_y,self.bbh_y)
                    self.caozuo()
                    time.sleep(1)
                    # 选择文件
                    self.choose('./image/chooseFile.png')
                    time.sleep(1)
                    # 点击文件路径
                    locat = self.find("./image/open.png")
                    pyautogui.click(x=locat.x + 60, y=locat.y + 15)
                    time.sleep(1)
                    # 写文件路径
                    pyautogui.typewrite(folder_path)
                    time.sleep(1)
                    # 之后回车
                    pyautogui.press('enter')
                    # 点击文件名输入框
                    self.choose('./image/name.png')
                    # 输入文件名
                    pyautogui.typewrite(file)
                    # 选择打开
                    self.choose('./image/openfile.png')
                    time.sleep(1)
                    pyautogui.press('enter')
                    time.sleep(20)
                    self.gouxuan()
                    self.choose('./image/Perform.png')

                    log_path = f'{self.rizhiFile}'
                    # 文件下载完成
                    # self.target_value = "|   结果 | 相同                 |"
                    # self.target_value = "运行完成"
                    # self.target_value_otp = "载入FLASH失败！"
                    self.target_value_jiaoyan= "对比校验和 成功！"
                    self.error_value = "失败!"
                    # eraseFailure = "全片擦除失败！"
                    i = 1
                    # 打开日志文件，
                    with open(log_path, 'r') as log_path_file:
                        while (i):
                            content = log_path_file.read()
                            # if self.target_value_otp in content:
                            #     time.sleep(0.5)
                            #     pyautogui.press('enter')
                            # else:
                            #     if self.target_value in content:
                            #         i = 0
                            #         time.sleep(0.5)
                            #     elif self.error_value in content:
                            #         time.sleep(0.5)
                            #         i = 0
                            if self.target_value_jiaoyan in content:
                                time.sleep(0.5)
                                pyautogui.press('enter')
                                i=0

                    # self.chongfu('./image/chongfu2.png')
                    time.sleep(2)
                    pyautogui.press('enter')
                    self.app.connect(self.XPXH, self.BBH,self.password)
                    time.sleep(2)
                    self.readfile(file,self.name)
        except FileNotFoundError:
            print("找不到指定的文件夹:", folder_path)


if __name__ == "__main__":
    downloader = downloader()
    current_time = datetime.time
    print(datetime.datetime.now())
    dataInfo = None
    # comName = downloader.gpt.getCOMPort("CH340")
    data = json.load(open('test_1.2.14.0.3.json', 'r', encoding='utf-8'))
    for item in data:
        downloader.name = item.get("name")
        downloader.allname = item.get("allname")
        downloader.add = item.get("add")
        downloader.bank = item.get("bank")
        downloader.length = item.get("length")
        downloader.XPXH = item.get("XPXH")
        downloader.BBH = item.get("BBH")
        downloader.way = item.get("way")
        downloader.jtag = item.get("jtag")
        downloader.password = item.get("password")
        downloader.xpxh_y = item.get("xpxh_y")
        downloader.bbh_y = item.get("bbh_y")
        # downloader.gpt.jtag_port(comName,downloader.jtag)
        time.sleep(1)
        # downloader.gouxuan()
        folder_path = f'D:/hx_downloader_tool/downloader/case/{downloader.name}'
        downloader.list_files_in_folder(folder_path)

